package com.rd.teacher.jichao.day15;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestCondition {

    public static void main(String[] args) {

        MyList list = new MyList();
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread1(list, lock, condition).start();
        new Thread2(list, lock, condition).start();
    }
}

class MyList {

    private List<String> list = new ArrayList<>();

    public void add(String str) {
        list.add(str);
    }

    public int size() {
        return list.size();
    }
}

class Thread1 extends Thread {
    MyList list;
    ReentrantLock lock;
    Condition condition;

    public Thread1(MyList list, ReentrantLock lock, Condition condition) {
        this.list = list;
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        try {
            // 先创建一个对象  作为锁
            // 使用synchronized将对象锁住
            // 在同步代码块中调用wait()方法
            // 等待其他线程运行  同时释放锁
            lock.lock();
            // 判断什么时候长度能等于5
            if (list.size() < 5) {
                System.out.println(getName() + "等待长度为5");
                condition.await();
                System.out.println(getName() + " wait被唤起");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class Thread2 extends Thread {
    MyList list;
    ReentrantLock lock;
    Condition condition;

    public Thread2(MyList list, ReentrantLock lock, Condition condition) {
        this.list = list;
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                list.add(i + "");
                System.out.println(getName() + "添加了元素 " + i);
                if (list.size() == 5) {
                    condition.signal();
                    System.out.println(getName() + "发出了通知");
                }
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}